<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="header">
      <h1>🚗 车牌识别系统</h1>
    </div>

    <!-- 上传区域 -->
    <div
        v-if="!selectedImage"
        class="upload-area"
        :class="{ 'drag-over': dragOver }"
        @click="handleUploadClick"
        @dragover.prevent="handleDragOver"
        @dragleave="handleDragLeave"
        @drop.prevent="handleDrop"
    >
      <i class="el-icon-upload2" style="font-size: 32px; color: #c0c4cc; margin-bottom: 10px;"></i>
      <p>点击选择图片或拖拽图片到此处</p>
      <p style="color: #909399; font-size: 14px;">支持格式: JPG, JPEG, PNG</p>
    </div>

    <input
        type="file"
        ref="fileInput"
        @change="handleFileSelect"
        accept="image/*"
        style="display: none;"
    />

    <!-- 图片预览 -->
    <div class="preview-container" v-if="selectedImage">
      <img id="preview" :src="previewUrl" alt="预览图片" />
      <div class="file-info">{{ fileInfo }}</div>
    </div>

    <!-- 操作按钮组 -->
    <div class="button-group">
      <button v-if="selectedImage" @click="clearImage" class="clear-btn">清空图片</button>
      <button v-if="selectedImage" @click="resetUpload" class="reset-btn">重新选择</button>
      <button v-if="selectedImage" @click="recognizePlate" :disabled="loading" class="recognize-btn">
        {{ loading ? '识别中...' : '识别车牌' }}
      </button>
    </div>

    <!-- 加载状态 -->
    <div class="loading" v-if="loading">
      <div class="spinner"></div>
      <p>正在识别中...</p>
    </div>

    <!-- 识别结果 -->
    <div v-if="resultMessage" :class="['result', resultType]">
      {{ resultMessage }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const fileInput = ref<HTMLInputElement | null>(null)
const selectedImage = ref<File | null>(null)
const previewUrl = ref('')
const fileInfo = ref('')
const loading = ref(false)
const resultMessage = ref('')
const resultType = ref('')
const dragOver = ref(false)

// 文件选择处理
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  if (!file.type.match('image.*')) {
    ElMessage.error('请选择图片文件！')
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过5MB！')
    return
  }

  fileInfo.value = `文件名: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`
  previewUrl.value = URL.createObjectURL(file)
  selectedImage.value = file

  if (fileInput.value) fileInput.value.value = ''
}

// 点击上传
const handleUploadClick = () => fileInput.value?.click()

// 拖拽事件
const handleDragOver = () => dragOver.value = true
const handleDragLeave = () => dragOver.value = false
const handleDrop = (event: DragEvent) => {
  dragOver.value = false
  const file = event.dataTransfer?.files[0]
  if (file) handleFileSelect({ target: { files: [file] } } as unknown as Event)
}

// 清空图片
const clearImage = () => {
  selectedImage.value = null
  previewUrl.value = ''
  fileInfo.value = ''
  resultMessage.value = ''
  resultType.value = ''
}

// 重新选择图片
const resetUpload = () => {
  clearImage()
  fileInput.value?.click()
}

// 识别车牌
const recognizePlate = async () => {
  if (!selectedImage.value) {
    ElMessage.error('请先选择一张图片')
    return
  }

  loading.value = true
  resultMessage.value = ''
  resultType.value = ''

  try {
    const formData = new FormData()
    formData.append('image', selectedImage.value)

    const res = await fetch('http://localhost:9032/api/car-plate/recognize', {
      method: 'POST',
      body: formData,
    })
    const result = await res.json()
    if (result.success) {
      let message = `识别结果: ${result.plateNumber}\n`;
      if (result.inPictureUrl) {
        message += `入场记录已创建\n`;
      }
      if (result.outPictureUrl) {
        message += `出场记录已更新\n`;
        message += `收费金额: ¥${result.portPrice}\n`;
      }
      message += result.message;
      
      resultMessage.value = message;
      resultType.value = 'success'
      ElMessage.success(message)
    } else {
      resultMessage.value = result.message
      resultType.value = 'error'
      ElMessage.error(result.message)
    }
  } catch (e: any) {
    console.error(e)
    resultMessage.value = '请求失败: ' + e.message
    resultType.value = 'error'
    ElMessage.error('请求失败: ' + e.message)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
body {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
  background-color: #f5f7fa;
  margin: 0;
  padding: 20px;
}

.app-container {
  max-width: 800px;
  margin: 50px auto 0; // 上边距 50px，下边距自动
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.upload-area {
  border: 2px dashed #c0c4cc;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  margin: 20px 0;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}
.upload-area:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}
.upload-area.drag-over {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.preview-container {
  text-align: center;
  margin: 20px 0;
}
#preview {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin: 0 auto;
}

.loading {
  text-align: center;
  margin: 20px 0;
}
.spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.result {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}
.success {
  background-color: #f0f9ff;
  color: #409eff;
  border: 1px solid #e1f5fe;
}
.error {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

.button-group {
  text-align: center;
  margin-top: 20px;
}
.button-group button {
  margin: 0 5px;
  width: 120px;
  height: 36px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.clear-btn {
  background-color: #dc3545;
  color: white;
}
.reset-btn {
  background-color: #ffc107;
  color: white;
}
.recognize-btn {
  background-color: #007bff;
  color: white;
}
.recognize-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}
</style>